//
//  FLNativeView.swift
//  Runner
//
//  Created by zhaoke on 2022/1/15.
//

import UIKit
import Foundation
import Flutter

class FLNativeViewFactory: NSObject, FlutterPlatformViewFactory {
    private var messenger: FlutterBinaryMessenger
    
    init(messenger: FlutterBinaryMessenger) {
        self.messenger = messenger
        super.init()
    }
    
    func create(
        withFrame frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: Any?
    ) -> FlutterPlatformView {
        return FLNativeView(
            frame: frame,
            viewIdentifier: viewId,
            arguments: args,
            binaryMessenger: messenger)
    }
}

class FLNativeView: NSObject, FlutterPlatformView {
    private var _view: UIView
    var showString: String?
    var nativeLabel: UILabel?
    var fChannerl: FlutterMethodChannel?
    init(
        frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: Any?,
        binaryMessenger messenger: FlutterBinaryMessenger?
    ) {
        _view = UIView()
        super.init()
        createNativeView(view: _view)
        let channel = FlutterMethodChannel.init(name: "plugins.methods/flnative_plugin", binaryMessenger: messenger!)
        channel.setMethodCallHandler({
            [weak self](call: FlutterMethodCall, result: FlutterResult) -> Void in
            let methodString = call.method
            let methodArgs = call.arguments
            if ("changeTextColor" == methodString) {
                self?.changeTextColor()
            } else if ("changeText" == methodString) {
                self?.changeText(args: methodArgs!)
            } else if ("openNativePage" == methodString) {
                self?.openNativeController(args: methodArgs!)
            }
        })
        self.fChannerl = channel
    }

    func view() -> UIView {
        return _view
    }

    func createNativeView(view _view: UIView){
        _view.backgroundColor = UIColor.lightGray
        //
        let nativeLabel = UILabel()
        nativeLabel.text = "Native text from iOS"
        nativeLabel.textColor = UIColor.white
        nativeLabel.textAlignment = .center
        nativeLabel.frame = CGRect(x: 0, y: 0, width: 180, height: 48.0)
        _view.addSubview(nativeLabel)
        self.nativeLabel = nativeLabel
        //
        let nativeBtn = UIButton(type: .custom)
        nativeBtn.setTitle("调用Flutter方法", for: .normal)
        nativeBtn.frame = CGRect(x: 16, y: 50, width: 200, height: 30)
        nativeBtn.setTitleColor(.white, for: .normal)
        nativeBtn.backgroundColor = .orange
        nativeBtn.addTarget(self, action: #selector(callFlutterMethodAction(sender:)), for: .touchUpInside)
        _view.addSubview(nativeBtn)
    }
}
fileprivate extension FLNativeView {
    func randomColor() -> UIColor {
        return UIColor(
            red: CGFloat(Float(arc4random_uniform(256)) / 255.0),
            green: CGFloat(Float(arc4random_uniform(256)) / 255.0),
            blue: CGFloat(Float(arc4random_uniform(256)) / 255.0),
            alpha: 1.0)
    }
    func changeTextColor() {
        self.nativeLabel!.textColor = self.randomColor()
    }
    func changeText(args: Any) {
        let temp = args as! NSArray
        if (temp.count > 0) {
            let params = temp[0] as! Dictionary<String, String>
            guard (params["showStr"] != nil) else {
                print("参数错误")
                return
            }
            let showStr = params["showStr"]
            self.nativeLabel?.text = showStr
        }
    }
    func openNativeController(args: Any) {
        let rootCtrl = UIApplication.shared.keyWindow?.rootViewController
        let testCtrl = NativeTestCtrl()
        rootCtrl?.present(testCtrl, animated: true, completion: nil)
    }
    @objc func callFlutterMethodAction(sender: UIButton) {
        self.fChannerl?.invokeMethod("callFlutterMethod", arguments: [ "showStr" : "this is string from native..." ])
    }
}
